package com.llcbenwu.util;

import com.llcbenwu.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import sun.dc.pr.PRError;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author lilinchun
 * @date 2021/11/16 0016 13:57
 */
@Component
public class AppSignUpUtils {

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 这个是创建数据库llc_userconnection 的连接的
     */
    @Resource
    private UsersConnectionRepository usersConnectionRepository;

    /**
     * 这个类是将ConnectionData转换成 Connection<?>作用
     */
    @Resource
    private ConnectionFactoryLocator connectionFactoryLocator;


    /**
     * 将社交账户信息存到redis
     * @param request
     * @param connectionData
     */
    public void  saveConnectData(WebRequest request, ConnectionData connectionData){
        redisTemplate.opsForValue().set(getKey(request),connectionData,10, TimeUnit.MINUTES);

    }

    /***
     * 从redis取出社交账户信息，并将其与本系统账户建立关联，并将关联关系存到数据库---userconnection表
     * @param request
     * @param userId
     */
    public  void dosignUp(WebRequest request,String userId){
      String key=getKey(request);
      if(StringUtils.isBlank(key)){
          throw  new BusinessException(1002,"无法找到缓存的第三方用户信息");
      }
      ConnectionData connectionData= (ConnectionData) redisTemplate.opsForValue().get(key);
      Connection<?> connection= connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId()).createConnection(connectionData);
      usersConnectionRepository.createConnectionRepository(userId).addConnection(connection);

      redisTemplate.delete(key);

    }
    /***
     * 根据请求头中的deviceId拼接一个存到redis中的key
     * @param request
     * @return
     */
    private String getKey(WebRequest request) {
        String deviceId=request.getHeader("deviceId");
        if(StringUtils.isBlank(deviceId)){
            throw new BusinessException(1001,"设备id不能为空");
        }
        return "security:social.connect."+deviceId;
    }


}
